var LOLMatrix={
    /*工具函数*/
    utils:{

        //获取url中的参数值
        getUrlParam:function (key) {
            var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null){
                r= unescape(r[2]);
            }
            return r;
        },

        //设置列表中的某个项为当前项，即当此项中data-val === value 时
        setCurClass:function(opt){
            var def={
                list:null,
                el:null,
                dataValName:'',
                value:'',
                clsName:'cur'
            };
            def=$.extend(def,opt);
            if(def.list.length<=0 || !def.value){return false;}

            var curEl=def.el;
            if(!curEl){
                def.list.each(function(index,item){
                    if($.trim($(item).data(def.dataValName))==def.value){
                        curEl=$(item);
                        return true;
                    }
                });
            }



            curEl.addClass(def.clsName).siblings().removeClass(def.clsName);
        }

    }
};

LOLMatrix.common = (function() {
    function showLoading() {
        var videoLoading$ = $('#ajaxLoading');
        if (videoLoading$.length <= 0) {
            $("body").append('<div class="ajax-loading flex-abs-mid " id="ajaxLoading" style="z-index:8500;position: fixed;"><img src="/res/images/cont/loaing.gif"></div>');
        } else {
            videoLoading$.show();
        }
    }
    function hideLoading() {
        $('#ajaxLoading').hide();
    }

    var lang = $('#langBox a.cur').data('lang');

    var _dialog = {
        showMask: function() {
            var mask = $(".p-page-mask");

            if (mask.length <= 0) {
                mask = $("<div class='p-page-mask'></div>");
                $("body").append(mask);
            } else {
                mask.show(0);
            }
        },
        hideMask: function() {
            var mask = $(".p-page-mask");
            mask.css({ "display": "none" });
        },

        //Displays page dialog box
        showDialog: function(dialog) {
            var me = this;
            if (dialog) {
                if (typeof dialog === 'string') {
                    dialog = $(dialog);
                }

                me.showMask();
                dialog.fadeIn(function () {
                    var inputs = $(':text,:password', dialog);
                    inputs.val('');
                    inputs.eq(0).focus();
                });

                dialog.delegate(".p-win-close", "click", function(e) {
                    e.preventDefault();
                    $('.valid-msg', dialog).hide().remove();
                    me.hideMask();
                    dialog.hide();
                });

            }
        },

        //Displays ajax loaded dialog box
        openDialog: function(options) {
            var finalOptions = $.extend({}, options);
            var me = this;
            if (!finalOptions.url) {
                return;
            }
            $.ajax({
                url: finalOptions.url,
                method: 'GET',
                beforeSend: showLoading
            }).done(function(htmlText) {
                var curDialog = $(htmlText);

                curDialog.undelegate('.btn-close,.p-win-close', 'click').delegate(".btn-close,.p-win-close", "click", function(e) {
                    e.preventDefault();
                    if (finalOptions.onClose) {
                        finalOptions.onClose.apply(curDialog);
                    } else {
                        me.hideMask();
                        curDialog.hide().remove();
                        curDialog = null;
                    }
                });

                $("body").append(curDialog);
                if (finalOptions.onLoad) {
                    finalOptions.onLoad.apply(curDialog);
                }

                me.showMask();
                curDialog.fadeIn();
            }).fail(function(responseText) {
                console.log(responseText);
            }).always(hideLoading);
        }
    };

    return {
        dialog: _dialog,
        //browser check for IE10-
        checkBrowser: function() {
            function createMask() {
                var browserMask = $("<div id='browserMast'></div>");
                browserMask.css({
                    "position": "absolute",
                    "left": 0, "right": 0, "top": 0, "bottom": 0,
                    "background": "#000",
                    'z-index': 10000
                });
                browserMask.html("" +
                    "<div style='margin: 200px auto 0 auto;  width:520px;text-align: left; font-size: 18px; color: #fff; line-height: 1.5em;'>" +
                    "<p>您的IE浏览器版本过低，请使用现代浏览器或IE10+，浏览本站。</p>" +
                    "<p><strong style='font-size: 14px; '>强烈推荐，使用下面的浏览器</strong></p>" +
                    "<p><a href='http://www.google.cn/intl/zh-CN/chrome/browser/desktop/index.html' target='_blank' style='color: #666;'>[Chrome]</a> " +
                    "<a href='http://www.firefox.com.cn/?www.firefoxchina.cn'  target='_blank' style='color: #666;'>[Firefox]</a> " +
                    "<a href='http://windows.microsoft.com/zh-cn/internet-explorer/download-ie'  target='_blank' style='color: #666;'>[IE11]</a> </p>" +
                    "</div>" +

                    "<div style='margin: 40px auto 0 auto;  width:520px;text-align: left; font-size: 18px; color: #00A000; line-height: 1.2em;'>" +
                    "<p>Your IE browser version is too low, please use a modern browser, or IE10+, visit this site</p>" +
                    "<p><strong style='font-size: 12px; '>Strongly recommend, use the following browser</strong></p>" +
                    "<p><a href='http://www.google.com/intl/en/chrome/browser/desktop/index.html' target='_blank' style='color: #666;'>[Chrome]</a> " +
                    "<a href='http://www.firefox.com/?www.firefoxchina.com'  target='_blank' style='color: #666;'>[Firefox]</a> " +
                    "<a href='http://windows.microsoft.com/en-ca/internet-explorer/download-ie'  target='_blank' style='color: #666;'>[IE11]</a> </p>" +
                    "</div>" +

                    "<div style='margin: 40px auto 0 auto;  width:520px;text-align: left; font-size: 16px; color: #3090cc; line-height: 1.5em;'>" +
                    "<p>您的IE瀏覽器版本過低，請使用現代瀏覽器或IE10+，流覽本站。</p>" +
                    "<p><strong style='font-size: 14px;'>強烈推薦，使用下面的瀏覽器</strong></p>" +
                    "<p><a href='http://www.google.com/intl/en/chrome/browser/desktop/index.html' target='_blank' style='color: #666;'>[Chrome]</a> " +
                    "<a href='http://www.firefox.com/?www.firefoxchina.com'  target='_blank' style='color: #666;'>[Firefox]</a> " +
                    "<a href='http://windows.microsoft.com/en-ca/internet-explorer/download-ie'  target='_blank' style='color: #666;'>[IE11]</a> </p>" +

                    "</div>" +
                    "");
                return browserMask;
            }
            // user jquery.browser
            if ($.browser.msie && parseInt($.browser.version) < 10) {
                $("html").css({ overflow: 'hidden' });
                var browserMask = createMask();
                $("body").css({ overflow: 'hidden' }).append(browserMask);
            }
        },

        //设置当前导航页
        setCurPage:function(){
            var pages={
                index:["","/","index","index.html","news","news.html"],
                news:["news","news.html","news-detail.html","news-detail"],
                match:["match","match.html","match-compare-detail","match-compare-detail.html"],
                teams:["teams","teams.html"],
                players:["players","players.html"],
                shop:["shop","shop.html"],
                game:["game","game.html"]
            };
            var curPage='index',
                curUrl= $.trim(location.href).toLowerCase(),
                curArr=[];
            for(var key in pages){
                curArr=pages[key];
                for(var i= 0,len=curArr.length;i<len;i++){
                    if(curUrl.indexOf(curArr[i])>=0){
                        curPage=key;
                        break;
                    }
                }
            }
            LOLMatrix.utils.setCurClass({
                list:$(".main-nav-item"),
                dataValName:'name',
                value:curPage,
                clsName:'cur'
            });
        },


        //form valid
        validMsg: function (container, json) {
            if (container.length <= 0) { return; }

            function showMsg(id, msg) {
                var ele = $("#" + id, container);
                if (ele.length === 0) {
                    ele = $("input[name='"+id+"']", container);
                }
                var item = ele.parent('.p-form-row');
                var validMessage$ = item.next('div.valid-msg');
              
                if (validMessage$.length === 0) {
                    validMessage$ = $('<div></div>', { "class": 'valid-msg flex-h', title: msg, text: msg });
                    item.after(validMessage$);
                } else {
                    validMessage$.attr({ title: msg }).html(msg);
                }
            }

            function showSummary(id, msg) {
                var ele = $(":submit,:button", container), item = null;
                item = $("form", container);
                var validMessage$ = item.prev('div.valid-msg');
                if (validMessage$.length === 0) {
                    validMessage$ = $('<div></div>', { "class": 'valid-msg flex-h', title: msg, text: msg });
                    item.before(validMessage$);
                } else {
                    validMessage$.attr({ title: msg }).html(msg);
                }
            }

            function hideMsg() {
                $(".valid-msg", container).hide().remove();
            }

            $.each(json, function (index, item) {
                //hideMsg();
                if (item.inputId === 'Summary') {
                    showSummary(item.inputId, item.msg);
                } else {
                    showMsg(item.inputId, item.msg);
                }
                
            });


            //on focus
            container.undelegate(':text,:password', 'focus').delegate(':text,:password', 'focus', function () {
                hideMsg();
            });
        },

        //nav hover
        navHover: function() {
            var navs = $(".main-nav-item").not($(".disabled-link"));
            navs.bind("mouseenter", function() {
                $(this).addClass('hover');
            }).bind("mouseleave", function() {
                    $(this).removeClass('hover');
                });

        },

        //Tabs,Switch, use the 'chagnetab' event
        tabs: function() {
            $(document).on('click', '.p-tab-h li', function(e) {
                e.preventDefault();
                var curClass = 'cur';
                var li$ = $(this).closest('li');
                var index = li$.index();
                li$.addClass(curClass).siblings().removeClass(curClass);
                li$.closest('.p-tab').find('.p-tab-c .p-tab-item').eq(index).show().siblings(':visible').hide();
                li$.trigger("changetab");
            });
        },


        //p-select
        pSelect:function(){
            var selectBox=$(".p-select"),
                selectHeader = $(".p-select-header",selectBox),
                selectBody = $(".p-select-body",selectBox);
            if (selectBox.length <= 0 ) {return;}


            function hideBody(curSelectBox) {
                $(".p-select-body",curSelectBox).removeClass("p-select-body-show");
            }
            function showBody(curSelectBox) {
                $(".p-select-body",curSelectBox).addClass("p-select-body-show");
            }

            selectHeader
                .on("mouseover", function (e) {
                    var curBox=$(this).parent('.p-select');
                    showBody(curBox);
                })
                .on("mouseleave", function (e) {
                var nextObj = e.relatedTarget,
                    eleTag = nextObj.tagName,
                   curBox=$(this).parent('.p-select');
                if (eleTag) {
                    if (eleTag === 'DIV') {
                        if (!$(nextObj).hasClass('p-select-body')) { hideBody(curBox); }
                    } else {
                        if (!$(nextObj).parents('div').hasClass('p-select-body')) { hideBody(curBox); }
                    }
                }
            });

            selectBody
                .on("mouseleave", function (e) {
                    var curBox=$(this).parent('.p-select');
                hideBody(curBox);
            })
                .on('click','li',function(e){
                    var me = $(this);
                    var curBox=me.parents('.p-select');
                    hideBody(curBox);
                    $(this).parents('.p-select-body').prev('.p-select-header').html(me.html());
                    me.trigger("changeOption");
            });

        },


        //Initial position of the sidebar
        backTopPositionX: function(posY) {
            var me = this;
            var backTop = $(".back-top"),
                backTopW = backTop.width(),
                pageW = $(document).width(),
                containerW = $(".container").width();



            // set top position
            function setTop() {
                var top = $(window).scrollTop();
                var locationFilterHeight = $('.location-filter').height();
                if (top > posY - locationFilterHeight) {
                    backTop.css({ 'position': 'fixed', top: 0 + locationFilterHeight });
                } else {
                    backTop.css({ 'position': 'absolute', top: posY });
                }
            }

            //firstLoad
            //Page width must be greater than the absolute width

            if (pageW <= containerW + backTopW * 2 + 30) {
                backTop.hide();
            } else {
                setTop();
               // backTop.css({ left: containerW + (pageW - containerW) / 2 }).fadeIn();
            }

            //window resize
            $(window).resize(function() {
                backTop.css({ "display": "none" });

                var curPageW = $(document).width();
                var curContainerW = $(".container").width();

                if (curPageW >= curContainerW + backTopW * 2 + 30) {
                    setTop();
                  //  backTop.show().css({ left: curContainerW + (curPageW - curContainerW) / 2 });
                    backTop.show();
                }
            });

            //scroll
            $(window).scroll(function() {
                setTop();
            });

            //back top 
            $(".back-top-btn a").bind("click", function () {
                $("html,body").animate({ scrollTop: 0 }, 300);
            });
      
            //upgrade
            $('.profile-cont .btn-detail, .upgrade').bind('click', function(e) {
                e.preventDefault();
                var dialog = LOLMatrix.common.dialog;
                if (dialog) {
                    dialog.showDialog($('#upgradeDialog'));
                }
            });
        },


        //set location filter position
        locationFilterPos: function () {
            var box = $(".location-filter"),
                nav=  $(".main-nav");
            if(box.length<=0){return;}
            var posY = box.position().top,
                boxH = box.innerHeight();



            // set top position
            function setTop() {
                var top = $(window).scrollTop();
                if (top > posY) {
                    box.css({ 'position': 'fixed', top: 0 });
                    nav.css({"padding-bottom":boxH});
                } else {
                    box.css({ 'position': 'relative', top: 0 });
                    nav.css({"padding-bottom":0});
                }
            }


            //scroll
            $(window).scroll(function () {
                setTop();
            });
        },


        getPosY: function() {
            var
                hdp = $(".hdp"),
                header = $("header"),
                nav = $("nav"),
                region = $(".location-filter"),
                posY = header.outerHeight() + nav.outerHeight() +region.outerHeight() || 0;

            posY += hdp.outerHeight();
            return posY;
        },

        //dialogs
        dialogCtrl: function() {
            //sign in
            $("#btnLogin, #btnSignIn").bind("click", function(e) {
                e.preventDefault();
                _dialog.showDialog($('div.user-login'));
            });

            //register 1
            $("#btnReg, #btnSignUp, .led .reg, .tbn .reg, .register").bind("click", function(e) {
                e.preventDefault();
                _dialog.showDialog($('div.user-reg'));
            });

            //register write password
            $("#userRegBtn").bind("click",function(e){
                e.preventDefault();
                $(".p-win").not('div.user-reg-pwd').fadeOut();
                _dialog.showDialog($('div.user-reg-pwd'));
            });

            //register ok
            $("#userRegPwdBtn").bind("click",function(e){
                e.preventDefault();
                $(".p-win").not('div.user-reg-ok').fadeOut();
                _dialog.showDialog($('div.user-reg-ok'));
            });

            //fast reg
            $("#fast-reg-btn").bind("click",function(e){
                e.preventDefault();
                $(".p-win").not('div.user-reg-pwd').fadeOut();
                _dialog.showDialog($('div.user-reg-pwd'));
            });
        },

        //Gets the current language
        getLang: function () {
            return lang;
        },

        //Get array max and min value
        getRange:function (data, diff) {
            var ret = { min: 0, max: 0 }, numArr = [];
            diff = diff || 50;
            $.each(data, function (index, item) {
                if (item.value) {
                    numArr.push(item.value * 1);
                } else {
                    numArr.push(item * 1);
                }
            });

            ret.max = Math.max.apply(null, numArr) + diff;
            ret.min = Math.min.apply(null, numArr);
            return ret;
        },

        convertDate: function(context) {
            $('.need-convert', context).each(function(index, element) {
                var format = $(this).hasClass('date-only') ? 'YYYY-MM-DD' : 'YYYY-MM-DD HH:mm';
                var element$ = $(element);
                var localTimeString = moment.utc(element$.text()).local().format(format);
                element$.removeClass('need-convert').text(localTimeString);
            });
        },

        formatDate: function(utcDate, dateOnly) {
            var format = dateOnly ? 'YYYY-MM-DD' : 'YYYY-MM-DD HH:mm';
            return moment.utc(utcDate).local().format(format);
        },

        formatLeftTime: function(utcDate) {
            function localize(started, day, hour, min) {
                var resources;
                switch (lang) {
                case 'zh-CN':
                    resources = ['进行中', '剩', '天', '小时', '分钟', ''];
                    break;
                case 'zh-TW':
                    resources = ['進行中', '剩', '天', '小時', '分鐘', ''];
                    break;
                default:
                    resources = ['Started', '', ' day ', ' hr ', ' min ', 'left'];
                    break;
                }
                if (started) {
                    return resources[0];
                }

                var result = resources[1];
                if (day != null) {
                    result += day + resources[2];
                }
                if (hour != null) {
                    result += hour + resources[3];
                }
                if (min != null) {
                    result += min + resources[4];
                }
                return result + resources[5];
            }

            var oneHour = 60;
            var oneDay = oneHour * 24;
            var diff = moment.utc(utcDate).diff(new Date(), 'minutes');
            if (diff < 0) {
                return localize(true);
            } else if (diff < oneHour) {
                return localize(false, null, null, diff % oneHour);
            } else if (diff < oneDay) {
                return localize(false, null, Math.floor(diff / oneHour), diff % oneHour);
            } else {
                return localize(false, Math.floor(diff / oneDay), Math.floor((diff % oneDay) / oneHour), null);
            }
        }
    }
})();


LOLMatrix.template = (function($) {
    // ReSharper disable once InconsistentNaming
    function Renderer(options) {
        var me = this;
        var state = { pageIndex: 1 };

        var defaultOptions = {
            method: 'GET',
            pageable: true
        };
        var finalOptions = $.extend({}, defaultOptions, options);
        var compiledTemplate = _.template($(finalOptions.template).html(), { variable: 'data' });
        var container$ = $(finalOptions.container);
        var updateView;
        if (finalOptions.pageable) {
            var pager$ = createPager();
            updateView = function() {
                if (state.pageIndex > 1 && state.pageIndex > state.total) {
                    //go to the first page and reload data
                    pager$.jqPagination('option', 'current_page', 1);
                } else {
                    pager$.jqPagination('option', {
                        trigger: false,
                        max_page: state.total
                    });
                    transitView();
                }
            }
        } else {
            updateView = transitView;
        }

        if (finalOptions.data) {
            bindData(finalOptions.data);
        }

        if (_.isFunction(finalOptions.localSort)) {
            state.compareFunction = finalOptions.localSort;
        } else if (finalOptions.localSort === true) {
            state.compareFunction = function(a, b, sortBy) {
                return a[sortBy] > b[sortBy] ? 1 : (a[sortBy] < b[sortBy] ? -1 : 0);
            }
        }

        if (finalOptions.sortableHeader) {
            var header$ = $(finalOptions.sortableHeader);
            header$.find('.sortable').click(function() {
                var col$ = $(this);
                if (col$.hasClass('asc') || col$.hasClass('desc')) {
                    col$.toggleClass('asc desc');
                } else {
                    header$.find('.sortable.asc, .sortable.desc').removeClass('asc desc');
                    col$.addClass('desc');
                }
                state.sortOption = {
                    sortBy: col$.data('column'),
                    desc: col$.hasClass('desc')
                };
                if (state.compareFunction) {
                    // we sort state.data directly, so that when filter is applied, the filtered result is sorted.
                    state.data.sort(function(a, b) {
                        var result = state.compareFunction(a, b, state.sortOption.sortBy);
                        if (state.sortOption.desc) {
                            result = 0 - result;
                        }
                        return result;
                    });
                    // since we sort state.data directly, if there is a filter, we shuld filter state.data again
                    if (state.predicate) {
                        state.filteredData = _.filter(state.data, state.predicate);
                    }
                    updateView();
                } else {
                    triggerLoadData();
                }
            });
        }

        function bindData(response) {
            if (response.Success) {
                state.filteredData = null;
                state.data = response.Data;
                if (_.isNumber(response.Total)) {
                    state.total = Math.max(response.Total, 1);
                }
                updateView();
            } else {
                console.error(response.Message);
            }
        }

        function getDataToRender() {
            return state.filteredData || state.data;
        }

        function createPager() {
            var element$ = $('<div class="page-bar">' +
                '<div class="pagination">' +
                '<a href="#" class="first" data-action="first">&laquo;</a>' +
                '<a href="#" class="previous" data-action="previous">&lsaquo;</a>' +
                '<input type="text" readonly="readonly" data-max-page="1" />' +
                '<a href="#" class="next" data-action="next">&rsaquo;</a>' +
                '<a href="#" class="last" data-action="last">&raquo;</a>' +
                '</div>' +
                '</div>').insertAfter(container$);
            element$.jqPagination({
                paged: function(pageIndex) {
                    state.pageIndex = pageIndex;
                    triggerLoadData();
                }
            });

            return element$;
        }

        function showSpinner() {
            var spinner$ = container$.nextAll('.ajax-loading');
            if (spinner$.length === 0) {
                $('<div class="ajax-loading"><span></span></div>').insertAfter(container$);
            } else {
                spinner$.show();
            }
        }

        function hideSpinner() {
            container$.nextAll('.ajax-loading').hide();
        }

        function transitView() {
            container$.html(compiledTemplate(getDataToRender()))
                .css({ opacity: 0, height: container$.innerHeight() })
                .animate({ opacity: 1 }, "fast")
                .promise()
                .done(function () { container$.css({ height: 'auto' }) });

            if (finalOptions.callback) {
                finalOptions.callback.apply(container$);
            }
        }

        function triggerLoadData() {
            if (!finalOptions.url) {
                return;
            }
            var requestParam = {};
            if (finalOptions.pageable) {
                requestParam.pageIndex = state.pageIndex;
            }

            if (finalOptions.query) {
                $.extend(requestParam, state.sortOption, finalOptions.query.call(this));
            }

            $.ajax({
                url: finalOptions.url,
                data: requestParam,
                method: finalOptions.method,
                beforeSend: showSpinner
            }).done(function(response) {
                bindData(response);
            }).fail(function(response) {
                console.log(response);
            }).always(hideSpinner);
        }

        me._render = function() {
            triggerLoadData();
            return {
                // reload data from server
                reload: function() {
                    triggerLoadData();
                },

                /**
                 * @param {null|function} predicate - a predicate to filter the local data. It assumes that state.data is an array
                 *                                    if it's null, it will clear the filter
                 */
                filterLocalData: function(predicate) {
                    state.predicate = predicate;
                    if (state.data) {
                        if (predicate && _.isFunction(predicate)) {
                            state.filteredData = _.filter(state.data, predicate);
                        } else {
                            state.filteredData = null;
                        }
                        updateView();
                    }
                }
            }
        };
    }

    return {

        /**
         * @param {Object} options
         * @param {string} options.container - the selector to the container to which the template will be rendered
         * @param {string} options.template - the selector to the underscore template which is put in <script type="text/template"></script>
         *                                    the data will put in the single variable "data" (_.template('template string', {variable: 'data'}))
         * @param {Object} [options.data] - the initial data to render the template
         * @param {string} [options.url] - the url to the remote service. The response should be the json of ESports.Common.Web.Result or ESports.Common.Web.PagedResult
         *                                 if options.data is omitted, this parameter is required.
         * @param {string} [options.method='GET'] - the HTTP method ('GET', 'POST', etc.)
         * @param {function} [options.query] - the function will returns additional parameters which are sent to the remote service.
         * @param {boolean} [options.pageable=true] - whether to show the pagination bar
         *                                            when the page is changed, {pageIndex: number} will be sent to the remote service
         * @param {string} [options.sortableHeader] - the selector to the sortable header which contains elements with 'sortable' class.
         *                                            the sortable elements should specified its column name in 'data-column' attribute
         *                                            this control will listen to the 'click' event of 'sortable' elements and will manage the sort state ('asc', 'desc' classes)
         * @param {boolean|function} [options.localSort] - whether to sort the data locally. It assumes that the data is a collection.
         *                                                 when it is true, it will use the default compare function to compare two items
         *                                                 when it is a function, this function is called to compare two items.
         *                                                 the signature of the function is: function(a, b, sortBy)
         *                                         If this function is not provided, {sortBy: 'column name', desc: true|false} will be sent to the remote service
         * @returns {Object} view
         *          {function} view.reload - tell the control to send request to the remote service to reload the data
         *          {function} view.filterLocalData - provide a function to filter the local data
         */
        render: function(options) {
            var renderer = new Renderer(options);
            return renderer._render();
        }
    };
})(jQuery);

$(function() {
    var base = LOLMatrix.common;
    base.checkBrowser();

    //test
    base.setCurPage();
    //test

    base.navHover();
    base.tabs();
    base.pSelect();

    var posY = base.getPosY()+70;
    base.backTopPositionX(posY);
    base.locationFilterPos();

    base.dialogCtrl();
    base.convertDate();
});
